package com.itcam.thread_.single_design;

public class SingleDesignDemo2 {
    /*
        单例设计模式 - 懒汉式 (延迟加载模式)

        --------------------------------------------------

            class Single2 {

                private Single2() {
                }

                private static Single2 s;

                public static Single2 getInstance() {
                    if (s == null) {
                        s = new Single2();
                    }
                    return s;
                }

            }

            弊端: 在多线程并发操作的时候, 有可能创建出多个对象.

        --------------------------------------------------

            class Single2 {

                private Single2() {
                }

                private static Single2 s;

                public static Single2 getInstance() {
                    synchronized (Single2.class) {
                        if (s == null) {
                            s = new Single2();
                        }
                    }
                    return s;
                }

            }

            弊端: 效率非常低

        --------------------------------------------------
     */
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Single2 s = Single2.getInstance();
                    System.out.println(s);
                }
            }).start();
        }
    }
}

class Single2 {

    private Single2() {
    }

    private static Single2 s;

    public static Single2 getInstance() {
        // 线程2
        // 线程1
        if (s == null) {
            synchronized (Single2.class) {
                if (s == null) {
                    s = new Single2();
                }
            }
        }

        return s;
    }

}